<?php

namespace app\admin\controller;

use app\admin\controller\Backend;
use fast\Form;

class Module extends Backend
{
	public function _initialize() {
		parent::_initialize();
		$this->model = model('admin/module', 'service');
	}

	public function index() {
		$param = $this->request->param();
		if ($this->request->isAjax()) {
			$result = $this->model->fetch_all(true);
			return $this->success('Operation completed', null, $result);
		}
		return $this->view->fetch();
	}

	public function install() {
		$identifier = $this->request->param('identifier');
		$result = $this->model->execute($identifier, 'install');
		if($result === false) {
			return $this->error($this->model->getError());
		}
		return $this->success(__('Operation completed'));
	}

	public function uninstall() {
		$identifier = $this->request->param('identifier');
		$result = $this->model->execute($identifier, 'uninstall');
		if($result === false) {
			return $this->error($this->model->getError());
		}
		return $this->success(__('Operation completed'));
	}

	public function upgrade() {
		$identifier = $this->request->param('identifier', 'upgrade');
		$result = $this->model->execute($identifier);
		if($result === false) {
			return $this->error($this->model->getError());
		}
		return $this->success(__('Operation completed'));
	}

	/* 配置 */
	public function config() {
		$identifier = $this->request->param('identifier');
		$info = $this->model->find(['identifier' => $identifier]);
		if($info === false) {
			return $this->error($this->model->getError());
		}
		if($info['status'] == -1) {
			return $this->error(__('该模块尚未安装'));
		}
		if($this->request->isPost()) {
			$param = $this->request->param();
			$result = $this->model->config($identifier, $param);
			if($result === false) {
				return $this->error($this->model->getError());
			}
			return $this->success(__('Operation completed'));
		} else {
			return $this->view->assign('info', $info)->fetch();
		}
	}

	public function clear() {
		$this->model->clear();
		return $this->success(lang('Operation completed'));
	}
}